﻿using AutoMapper;
using JunionRobotTaskManager.Dtos;
using JunionRobotTaskManager.Models;
using JunionRobotTaskManager.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Redbus.Interfaces;
using SqlSugar;

namespace JunionRobotTaskManager.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DockController : Controller
    {


        #region  Filed

        private readonly ILogger<DockController> _logger;

        private readonly IDockRepository _dockRepository;

        private readonly IEventBus _eventBus;

        #endregion

        public DockController(ILogger<DockController> logger,
            IDockRepository dockRepository,
            IEventBus mCache)
        {
            _logger = logger;
            _dockRepository = dockRepository;
            _eventBus = mCache;
        }


        #region 创建



        /// <summary>
        /// 创建Dock信息
        /// </summary>
        /// <param name="dockInfo">新的Dock信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<ApiResult>> Create([FromBody] Dock dockInfo)
        {
            try
            {
                if (!await _dockRepository.AddAsync(dockInfo))
                    return ApiResultHelper.Error("添加失败，服务器发生错误");
                else
                    _eventBus.Publish<BusMessage>(new BusMessage("Dock", Operation.Add, dockInfo));

                return ApiResultHelper.Success(dockInfo);
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"添加出错!服务器发生错误:{ex.Message}");
            }


        }

        [HttpPost]
        public async Task<ActionResult<ApiResult>> Import( List<Dock> docks)
        {
            try
            {
            

                var ids = docks.Select(x => x.Id).ToList();
                var existsId = _dockRepository.Query(x => ids.Contains(x.Id)).Select(x => x.Id);
                var upDocks = docks.Where(x => existsId.Contains(x.Id)).ToList();
                var addDocks = docks.Where(x => !existsId.Contains(x.Id)).ToList();

                if (upDocks.Any())
                {
                    if (!await _dockRepository.UpdateListAsync(upDocks))
                        return ApiResultHelper.Error("添加失败，服务器发生错误");
                }

                if (addDocks.Any())
                {
                    if (!await _dockRepository.AddListAsync(addDocks))
                        return ApiResultHelper.Error("添加失败，服务器发生错误");
                }


                return ApiResultHelper.Success(0);
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"添加出错!服务器发生错误:{ex.Message}");
            }
        }
        #endregion

        #region 更新
        /// <summary>
        /// 更新Dock信息
        /// </summary>
        /// <param name="id">Dock的Id</param>
        /// <param name="dockInfo">新的dock信息</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ApiResult> Update(string id, Dock dockInfo)
        {
            if (! _dockRepository.CheckExist(x=>x.Id==id)) 
                return ApiResultHelper.Error("没有找到该Dock信息");
          
            if (!await _dockRepository.UpdateEntityAsync(dockInfo))
                return ApiResultHelper.Error("修改失败");
            else
                _eventBus.Publish<BusMessage>(BusMessage.UpdateCreate("Dock", dockInfo));
            return ApiResultHelper.Success(dockInfo);
        }



        /// <summary>
        /// 释放Dock点
        /// </summary>
        /// <returns></returns>
        [HttpPatch("{id}/{enable}")]
        public async Task<ActionResult<ApiResult>> Occupied(string id, bool enable)
        {
            var dockInfo = await _dockRepository.FindByIdAsync(id);
            if (dockInfo == null) return ApiResultHelper.Error("没有找到该设备");
            dockInfo.IsOccupied = enable;

            bool b = await _dockRepository.UpdateEntityAsync(dockInfo);
            if (!b)
                return ApiResultHelper.Error("修改失败");
            else
                _eventBus.Publish<BusMessage>(new BusMessage("Dock", Operation.Update, dockInfo));
            return ApiResultHelper.Success(dockInfo);
        }

        /// <summary>
        /// 启用Dock点
        /// </summary>
        /// <returns></returns>
        [HttpPatch("{id}/{enable}")]
        public async Task<ActionResult<ApiResult>> Enable(string id, bool enable)
        {
            var dockInfo = await _dockRepository.FindByIdAsync(id);
            if (dockInfo == null) return ApiResultHelper.Error("没有找到该设备");
            dockInfo.Enable = enable;

            bool b = await _dockRepository.UpdateEntityAsync(dockInfo);
            if (!b)
                return ApiResultHelper.Error("修改失败");
            else
                _eventBus.Publish<BusMessage>(new BusMessage("Dock", Operation.Update, dockInfo));
            return ApiResultHelper.Success(dockInfo);
        }


        #endregion

        #region 删除


        /// <summary>
        /// 删除Dock点通过Id
        /// </summary>
        /// <param name="id">Dock的Id</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResult>> Delete(string id)
        {
            if (!await _dockRepository.DeleteByIdAsync(id))
                return ApiResultHelper.Error("删除失败");
            else
                _eventBus.Publish<BusMessage>(new BusMessage("Dock", Operation.Delete, id));

            return ApiResultHelper.Success("success");
        }

        /// <summary>
        /// 批量删除Dock点
        /// </summary>
        /// <param name="ids">要删除的Dock</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult<ApiResult>> DeleteByIds(string[] ids)
        {
            if (!await _dockRepository.DeleteByIdsAsync(ids))
                return ApiResultHelper.Error("删除失败");
            else
                _eventBus.Publish<BusMessage>(BusMessage.DeleteCreate("Dock", ids));
            return ApiResultHelper.Success("success");
        }


        #endregion

        #region 查找 

        /// <summary>
        /// 分页查找
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页大小</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetDocksByPage(int page, int limit, [FromQuery] string query)
        {
            RefAsync<int> total = 0;
            try
            {
                if (query != null)
                {
                    JObject jobject = JObject.Parse(query);
                    List<IConditionalModel> models = new List<IConditionalModel>();
                    foreach (var key in jobject.Properties())
                    {

                        models.Add(new ConditionalModel()
                        { FieldName = key.Name, FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.Equal });


                    }
                    var docks = await _dockRepository.QueryAsync(models, page, limit, total);

                    return ApiResultHelper.Success(docks, total);
                }
                else
                {
                    var docks = await _dockRepository.QueryAsync(page, limit, total);


                    return ApiResultHelper.Success(docks, total);
                }
            }
            catch (Exception ex)
            {
                return ApiResultHelper.Error($"查询出错:{ex.Message}");
            }
        }


        /// <summary>
        /// 检测是否存在
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet("{query}")]
        public async Task<ActionResult<ApiResult>> Check(string query)
        {

            try
            {
                if (query.Contains("id"))
                {
                    var data = await _dockRepository.QueryAsync(x => query.Contains(x.Id));
                    return ApiResultHelper.Success(data.Count);
                }
                else
                {
                    return ApiResultHelper.Error("查询字符串不对");
                }

            }
            catch (Exception e)
            {
                return ApiResultHelper.Error("查找Park点出错" + e.Message);
            }

        }
        #endregion

    }
}
